package com.zrf.kafka.main;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

/**
 * @author zhouruifeng
 * @date 2018/5/17
 */
public class KfkProducer extends Thread {
    private final Producer<Integer, String> producer;
    private final String topic;
    private final Properties props = new Properties();

    public KfkProducer(String topic) {
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, KfkConfig.kafkaServerURL);
        props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");
        props.put(ConsumerConfig.GROUP_ID_CONFIG, KfkConfig.groupId);
        producer = new KafkaProducer(props, new StringSerializer(), new StringSerializer());
        this.topic = topic;
    }

    @Override
    public void run() {
        int messageNo = 1;
        for (; messageNo < 100; messageNo++) {
            String messageStr = new String("Message_" + messageNo);
            try {
                producer.send(new ProducerRecord(topic, messageStr)).get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            System.out.println("Send:" + messageStr);
        }
        producer.close();
    }
}
